package com.itheima.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itheima.utils.BaseAction;
import com.opensymphony.xwork2.ActionContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import itcast.bos.domain.base.PageBean;
import itcast.bos.domain.base.Promotion;
import itcast.bos.domain.finaldemo.FinalDemo;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@SuppressWarnings("all")
public class PromotionAction extends BaseAction<Promotion> {

	@Action(value = "findPromotionDetail",results={@Result(name="success",type="redirect",location="")})
	public String findDetail() throws Exception {
		// 拿到有没有这个id对应的网页
		String freePath = ServletActionContext.getServletContext().getRealPath("/freemarker");
		// 创建出id对应的文件
		File file = new File(freePath + "/" + model.getId() + ".html");
		// 判断是否存在
		System.out.println("进入了findprodetail的action");
		if (!file.exists()) {
			// 根据id查找到这个对象
			Promotion promotion = WebClient.create(FinalDemo.Bos_Url+"/bos_management/services/promotionService/findOne?id="+model.getId()).get(Promotion.class);
			System.out.println("宣传描述=--------"+promotion.getDescription());
			// 给这个文件赋值
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
			configuration.setDirectoryForTemplateLoading(new File(ServletActionContext.getServletContext()
					.getRealPath("/WEB-INF/freemarker_templates")));
			Template template = configuration.getTemplate("promotion_detail.ftl");
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("promotion", promotion);
			template.process(map, new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
			//return NONE;
		}
		FileUtils.copyFile(file, ServletActionContext.getResponse().getOutputStream());
		return NONE;
	}

	@Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
	public String name() {
		System.out.println("page----------" + page + "-------rows----------" + rows);
		PageBean<Promotion> pa = WebClient
				.create("http://localhost:8080/bos_management/services/promotionService/pageQuery?page=" + page
						+ "&rows=" + rows)
				.accept(MediaType.APPLICATION_JSON).get(PageBean.class);
		ActionContext.getContext().getValueStack().push(pa);
		return SUCCESS;
	}
}
